<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Results extends CI_Controller {
		public function index()
		{
			$voteobj = new Vote();
			$voteobj->where("ip_addr", $_SERVER['REMOTE_ADDR']);
			$pobj = new Previousoption();
			$pobj->select_max("date");
			$pobj->limit(1);
			$pobj->get();
			if (isset($_POST["place"]) && !empty($_POST["place"]))
			{
				$placeobj = new Place();
				//$voteobj = new Vote();
				$placeobj->get_by_id($_POST["place"]);
				$newvote = new Vote();
				$resultarr = array();
				$voteobj->where("date", $pobj->date);
				$voteobj->get();
				if (!$voteobj->exists())
				{
					$newvote->ip_addr = $_SERVER['REMOTE_ADDR'];
					$newvote->date = $pobj->date;
					//$newvote->place->id = 2;
					$newvote->save($placeobj);
					
					echo "Vote saved! <br/>";
				} else {
					$voteobj->save($placeobj);
					echo "Vote updated! <br/>";
				}
				$this->showvotes($pobj->date);
			} else {
				//no peeking!
				//get current date from previous options
				$this->showvotes($pobj->date);
				
			}
		}
		private function showvotes($date)
		{
			$results = new Vote();
			$results->where("date", $date)->get();
			foreach($results as $result)
			{
				if (isset($resultarr[$result->place->place]))
					$resultarr[$result->place->place] += 1;
				else
					$resultarr[$result->place->place] = 1;
			}
			echo "<br><br>";
			foreach($resultarr as $key=>$val)
				echo $key . " => " . $val . "<br>";
		}
}

?>